package com.example.model;

import java.sql.*;
import java.util.*;

public class WrongQuestionDAO {
    private Connection conn;
    public WrongQuestionDAO(Connection conn) {
        this.conn = conn;
    }
    // 添加错题（避免重复）
    public void addWrongQuestion(int userId, int questionId) throws SQLException {
        String sql = "INSERT IGNORE INTO wrong_questions (user_id, question_id) VALUES (?, ?)";
        try (PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setInt(1, userId);
            ps.setInt(2, questionId);
            ps.executeUpdate();
        }
    }
    // 删除错题
    public void deleteWrongQuestion(int userId, int questionId) throws SQLException {
        String sql = "DELETE FROM wrong_questions WHERE user_id=? AND question_id=?";
        try (PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setInt(1, userId);
            ps.setInt(2, questionId);
            ps.executeUpdate();
        }
    }
    // 分页查询错题（带题目信息）
    public List<Map<String, Object>> getWrongQuestions(int userId, int offset, int pageSize) throws SQLException {
        String sql = "SELECT w.id, w.question_id, w.wrong_time, q.question, q.option_a, q.option_b, q.option_c, q.option_d, q.answer, q.explanation " +
                "FROM wrong_questions w JOIN quiz_questions q ON w.question_id = q.id WHERE w.user_id=? ORDER BY w.wrong_time DESC LIMIT ?, ?";
        List<Map<String, Object>> list = new ArrayList<>();
        try (PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setInt(1, userId);
            ps.setInt(2, offset);
            ps.setInt(3, pageSize);
            try (ResultSet rs = ps.executeQuery()) {
                while (rs.next()) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("id", rs.getInt("id"));
                    map.put("questionId", rs.getInt("question_id"));
                    map.put("wrongTime", rs.getTimestamp("wrong_time"));
                    map.put("question", rs.getString("question"));
                    map.put("optionA", rs.getString("option_a"));
                    map.put("optionB", rs.getString("option_b"));
                    map.put("optionC", rs.getString("option_c"));
                    map.put("optionD", rs.getString("option_d"));
                    map.put("answer", rs.getString("answer"));
                    map.put("explanation", rs.getString("explanation"));
                    list.add(map);
                }
            }
        }
        return list;
    }
    // 查询错题总数
    public int countWrongQuestions(int userId) throws SQLException {
        String sql = "SELECT COUNT(*) FROM wrong_questions WHERE user_id=?";
        try (PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setInt(1, userId);
            try (ResultSet rs = ps.executeQuery()) {
                if (rs.next()) return rs.getInt(1);
            }
        }
        return 0;
    }
} 